import datetime
import Core.Gadget as Gadget
import Core.JDMySQLDB as JDMySQLDB
from SystematicFactors.General import *
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from WindPy import w


# ---本例介绍如何操作系统层因子---

# 从数据库读取因子
def LoadFactor(database,
               databaseName, # 库名
               tableName, # 表名
               factorName, # 因子名
               datetime1=None, datetime2=None): # 要读取的时间区间
    #
    filter = {"Name": factorName}
    if datetime1 != None and datetime2 != None:
        filter["Date"] = {">=": datetime1, "<=": datetime2}
    #
    data = database.Find(databaseName, tableName, filter, sort=[("Date", 1)])
    df = Gadget.DocumentsToDataFrame(data)
    df = df[["date", 'value']]

    # Process
    df['date'] = pd.to_datetime(df['date'])
    df.rename(columns={"value": factorName}, inplace=True)
    #
    return df


def Plot(database,
         databaseName,
         tableName,
         factorName,
         diff=False): # 是否差分后再Plot
    #
    df = LoadFactor(database, databaseName, tableName, factorName)
    #
    if diff:
        df[factorName] = df[factorName] - df[factorName].shift(1)

    df.plot(x="date", y=[factorName], grid=True, title=factorName)
    # ax1.set_ylabel('Net Unit Value')
    # print(df.describe())
    plt.show()


def Download_PriceLevel(database, datetime1, datetime2):
    # 请求Wind数据
    df_cpi = EDB('M0000612', datetime1, datetime2, field_name='CPI_YoY', dateAsIndex=True)
    print(df_cpi)

    # 补充发布日期
    df_cpi["Report_Date"] = df_cpi.index
    Fill_ReleaseDate(df_cpi, lag_release_month=1, release_day=10)
    print(df_cpi)

    # 储存原始数据
    # Save_Systmetic_Raw_To_Database(database, df_cpi, saved_name="M0000612", field_name="CPI_YoY")

    # 储存为因子数据
    Save_Systematic_Factor_To_Database(database, df_cpi, save_name='CPI_YoY_Test', field_name="CPI_YoY")


if __name__ == '__main__':

    config =  \
    {
      "factor": { "Username": "m_Factor", "Password":"mOaruP"}
    }

    # 连接数据库
    database = JDMySQLDB.JDMySQLDB("172.25.4.218", "3306", config=config)

    # 读取数据库因子，Plot
    # Plot(database, "Factor", "a_sys_factor", "IF_FutSpotBasis_Weighted")

    # 基于wind数据制作并储存因子
    w.start()
    datetime1 = datetime.datetime(2019, 1, 1)
    datetime2 = datetime.datetime(2020, 1, 1)
    Download_PriceLevel(database, datetime1, datetime2)
